<template>
  <div class="p-4">
    <div class="job-container-wrap">
      <div class="top-mod">
        <div class="calendar">
          <a-calendar v-model:value="dateValue"
            :fullscreen="false"
            @panelChange="onPanelChange"
            @change="calendarChange"
          >
            <template #headerRender="{ value: current, onChange }">
              <div class="calendar-top">
                <div class="title-wrap">
                  <div class="title">任务管理</div>
                  <a-select
                    :dropdown-match-select-width="false"
                    class="my-year-select"
                    :value="String(current.year())"
                    @change="
                      newYear => {
                        onChange(current.year(+newYear));
                      }
                    "
                  >
                    <a-select-option
                      v-for="val in getYears(current)"
                      :key="String(val)"
                      class="year-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    style="margin-left: 15px;"
                    :dropdown-match-select-width="false"
                    :value="String(current.month())"
                    @change="
                      selectedMonth => {
                        onChange(current.month(parseInt(String(selectedMonth), 10)));
                      }
                    "
                >
                    <a-select-option
                      v-for="(val, index) in getMonths(current)"
                      :key="String(index)"
                      class="month-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                </div>
              </div>
            </template>
          </a-calendar>
        </div>
      </div>
      <div class="table-wrap">
        <BasicTable @register="registerTable" :searchInfo="queryParam" >
          <template #bodyCell="{ record, column }">
            <!--  -->
            <template v-if="column.dataIndex === 'result'">
              <div class="resultWrap" @click="openDataManage(record)">
                <div class="resultStatus">
                  <template v-if="resultIcon('isShowIcon', record)"><a-badge :status="resultIcon('icon', record)" /></template>
                  {{ resultIcon('resultStatus', record) }}</div>
                <div class="resultNum" v-if="resultIcon('isShowIcon', record)"> {{ `(${record.status === TaskStatus.Success ? record.mediaCount : '0' }/${record.mediaCount || '0'})` }}</div>
              </div>
            </template>
            <template v-if="column.dataIndex === 'status'">
              <div class="statusWrap">
                <template v-if="resultIcon('isShowIcon', record)"><a-badge :status="resultIcon('icon', record)" /></template>
                <div class="text">{{ resultIcon('statusTxt', record) }}</div>
                <template v-if="record.status === TaskStatus.Failed">
                  <div class="tips">
                    <Tooltip
                      :title="record.result"
                    >
                      <span><InfoCircleOutlined /></span>
                    </Tooltip>
                  </div>
                </template>
              </div>
            </template>
          </template>
          <template #toolbar>
            <div class="toolbar">
              <div class="icon">
                <div class="icon-calendar" @click="() => router.push({ path: '/uav/jobList' })"><Icon icon="lucide:calendar"></Icon></div>
                <div class="icon-list"><Icon icon="gg:list"></Icon></div>
              </div>
              <a-button class="addTask" preIcon="ant-design:plus-outlined" @click="addTask"> 创建任务 </a-button>
              <a-select 
                style="width: 143px;" 
                v-model:value="queryParam.status" allowClear
                :options="optionsList.status" 
                @change="value => selectChange('status', value)"
              />
              <a-select 
                style="width: 143px;" v-model:value="queryParam.jobType"
                allowClear :options="optionsList.jobType"
                @change="value => selectChange('jobType', value)"
              />
              <a-input-search
                allowClear
                v-model:value="queryParam.jobName"
                placeholder="请搜索任务名称"
                style="width: 200px;"
                @search="enterSearch"
              />
            </div>
          </template>
          <template #action="{ record, column }">
            <TableAction
              :actions="createActions(record, column)"
              :dropDownActions="getDropDownActions(record)"
            />
          </template>
        </BasicTable>
      </div>
      <AddJob
        :pageType="pageType"
        :jobData="jobData"
        @success="success" 
        @register="registerAddJob" 
      />
      <TrackPlaybackModal
        :isCollapsed="true"
        :open="trackPlaybackOpen" 
        :trackPlaybackDeviceSn="trackPlaybackDeviceSn"
        @close="() => { trackPlaybackOpen = false }" 
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import AddJob from './addJob.vue'
import TrackPlaybackModal from '/@/views/components/flightPathReplay/trackPlaybackModal.vue';
import { inject, onMounted, reactive, watch, ref, computed, toRaw } from 'vue';
import { BasicTable, useTable, TableAction, EditRecordRow, BasicColumn, ActionItem, } from '/@/components/Table';
import { useMessage } from '/@/hooks/web/useMessage';
import ApiListOptions from '/@/api/type'
import { useRouter } from "vue-router";
import { TaskStatusOps, TaskStatus, TaskTypeOps, PageType } from '/@/constants/job'
import Icon from '/@/components/Icon/index';
import { useModal } from '/@/components/Modal';
import { Tooltip } from 'ant-design-vue';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { FolderOpenFilled } from '@ant-design/icons-vue';
import { DataDirNavigation } from '/@/constants/index'
import { throttle } from 'lodash-es'
import dayjs, { Dayjs } from 'dayjs';

const router = useRouter();

const optionsList = ref<any>({
  status: TaskStatusOps,
  jobType: TaskTypeOps
})
let queryParam = reactive<any>({
  year: dayjs().year(),
  month: dayjs().month() + 1,
  day: dayjs().date(),
  jobType: '',
  status: '',
  jobName: ''
})

const resultStatus: any[] = [{
  value: TaskStatus.Success,
  label: '上传成功'
},{
  value: TaskStatus.Progress,
  label: '等待上传'
},{
  value: TaskStatus.Failed,
  label: '上传失败'
}]

const iconList: any[] = [{
  value: TaskStatus.Success,
  icon: 'success'
},{
  value: TaskStatus.Progress,
  icon: 'processing'
},{
  value: TaskStatus.Failed,
  icon: 'error'
}]

const columns:BasicColumn[] = [
  {
    title: '计划时间',
    dataIndex: 'planTime',
    key: 'planTime',
    align: 'center',
  },
  {
    title: '任务名称',
    dataIndex: 'taskName',
    key: 'taskName',
    align: 'center',
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    // customRender: function ({ text }) {
    //   //console.log("执行状态--record", record)
    //   const statusList = optionsList.value.status
    //   return statusList.find(item => item.value === text)?.label || '-'
    // },
  },
  {
    title: '任务类型',
    dataIndex: 'jobType',
    key: 'jobType',
    align: 'center',
    customRender: function ({ text }) {
      const jobTypeList = optionsList.value.jobType
      return jobTypeList.find(item => item.value === text)?.label || '-'
    },
  },
  {
    title: '关联航线',
    dataIndex: 'waylineName',
    key: 'waylineName',
    align: 'center',
  },
  {
    title: '关联设备',
    dataIndex: 'deviceName',
    key: 'deviceName',
    align: 'center',
  },
  {
    title: '媒体上传',
    dataIndex: 'result',
    key: 'result',
    width: 180,
    align: 'center',
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    key: 'createBy',
    width: '150px',
    align: 'center',
  }
]
const $http: ApiListOptions | undefined = inject('api')
const { createMessage , createConfirm } = useMessage();

let trackPlaybackOpen = ref<boolean>(false); //轨迹回放弹窗
let trackPlaybackDeviceSn = ref() // 轨迹回放设备SN

const dateValue = ref<Dayjs>();
//注册table数据
const [registerTable, { reload, setProps }] = useTable({
    title: '',
    api: $http?.getTaskQureyTaskListByDay,
    rowKey: 'id',
    columns: columns,
    searchInfo: {
      ...queryParam
    },
    pagination: false,
    clickToRowSelect: false,
    striped: true,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    showActionColumn: true,
    actionColumn: {
      width: 280,
      title: '操作',
      fixed: 'right',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
});
const pageType = ref<string>('')
const jobData = ref<any>()
const [registerAddJob, { openModal: modalAddJob }] = useModal()
const dirList = ref<any[]>([])    // 数据管理的目录路径

const resultIcon = computed(() => 
  (type: string, record): any => {
    switch(type){
      case 'resultStatus':
        {
          return resultStatus.find(item => item.value === record.status)?.label || '-'
        }
      case 'isShowIcon':
        {
          return iconList.find(item => item.value === record.status)?.icon ? true : false
        }
      case 'icon':
        {
          return iconList.find(item => item.value === record.status)?.icon
        }
      case 'statusTxt':
        {
          return optionsList.value.status.find(item => item.value === record.status)?.label || '-'
        }
    }
  }
)

onMounted(() => {
  //console.log("初始化")
});

const onPanelChange = (value: Dayjs, mode: string) => {
  //console.log("onPanelChange==value", value.year(), value.month() + 1, value.date())
  queryParam.year = value.year()
  queryParam.month = value.month() + 1
  queryParam.day = value.date()
  searchQuery()
};

const calendarChange = (value: Dayjs, ) => {
  //console.log("calendarChange==value", value.year(), value.month() + 1, value.date())
  queryParam.year = value.year()
  queryParam.month = value.month() + 1
  queryParam.day = value.date()
  searchQuery()
}

const getMonths = (value: Dayjs) => {
  const localeData = value.localeData()
  const months = []
  for (let i = 0; i < 12; i++) {
    months.push(localeData.monthsShort(value.month(i)))
  }
  return months
};

const getYears = (value: Dayjs) => {
  const year = value.year();
  const years: any[] = [];
  for (let i = year - 10; i < year + 10; i += 1) {
    years.push(i);
  }
  return years;
};

const searchQuery = throttle(() => 
  {
    const params = { ...queryParam }
    Object.keys(params).forEach(key => {
      if(params[key] === '' || params[key] === null){
        params[key] = undefined
      }
    })
    setProps({ searchInfo: toRaw(params) })
    reload()
  }
, 1000)

const addTask = () => {
  pageType.value = PageType.Add
  modalAddJob(true)
}

//权限控制  true: 有权限  false: 无权限
const btnAuth = (type: string, record): boolean => {
  const { status } = record
  const btnAccess = {
    '编辑': [TaskStatus.NotStart, TaskStatus.Pending].includes(status),
    '复制': true,
    '删除': ![TaskStatus.Progress].includes(status),
    '挂起': [TaskStatus.NotStart].includes(status),
    '恢复': [TaskStatus.Pending].includes(status),
    '返航': [TaskStatus.Progress].includes(status),
    '查看轨迹': [TaskStatus.Success, TaskStatus.PartialSuccess].includes(status)
  }
  return btnAccess[type]
}

const createActions = (record: EditRecordRow, column: BasicColumn): ActionItem[] => {
  return [
    {
      label: '编辑',
      icon: "ep:edit",
      onClick: handleAction.bind(null, PageType.Edit, record),
      ifShow: btnAuth('编辑', record)
    },
    {
      label: '复制',
      icon: "radix-icons:copy",
      onClick: handleAction.bind(null, PageType.COPY, record),
      ifShow: btnAuth('复制', record)
    },
    {
      label: '删除',
      icon: "icon-park-outline:delete",
      onClick: handleAction.bind(null, 'del', record),
      ifShow: btnAuth('删除', record)
    },
  ];
}

const getDropDownActions = (record) => {
  const { jobId, deviceId } = record
    let arr = [
      {
        label: '挂起任务',
        popConfirm: {
          title: '是否挂起任务？',
          confirm: async () => {
            await $http?.postWaylinejobPause({ jobId })
            searchQuery()
          },
        },
        ifShow: btnAuth('挂起', record)
      },
      {
        label: '恢复任务',
        popConfirm: {
          title: '是否恢复任务？',
          confirm: async () => {
            await $http?.postWaylinejobResume({ jobId })
            searchQuery()
          },
        },
        ifShow: btnAuth('恢复', record)
      },
      {
        label: '返航',
        popConfirm: {
          title: '是否返航？',
          confirm: async () => {
            const result = await $http?.getDeviceShadowGet(deviceId)
            //console.log("getDeviceShadowGet--result", result)
            if(result){
              const { deviceSn } = result
              await $http?.postDeviceDebugInstructPost({
                deviceId: deviceId,
                deviceSn: deviceSn,
                instuct: "return_home",
                reqId: localStorage.getItem('wsClientId')
              })
              searchQuery()
            }
          },
        },
        ifShow: btnAuth('返航', record)
      },
      {
        label: '查看轨迹',
        onClick: handleAction.bind(null, 'viewWayLine', record),
        ifShow: btnAuth('查看轨迹', record)
      },
    ];
    return arr;
  };

const handleAction = async(type: string, record) => {
  //console.log("功能操作--record", type, record)
  const { jobId, deviceId } = record
  switch(type){
    case PageType.Edit:
      {
        const result = await $http?.getWaylinejobGet({ jobId })
        if(result){
          pageType.value = PageType.Edit
          jobData.value = { ...result, jobParameters: undefined }
          modalAddJob(true)
        }
      }
    break;
    case PageType.COPY:
      {
        const result = await $http?.getWaylinejobGet({ jobId })
        if(result){
          pageType.value = PageType.COPY
          jobData.value = { ...result, jobParameters: undefined }
          modalAddJob(true)
        }
      }
    break;
    case 'del':
      {
        createConfirm({
          title: '删除任务',
          content: '确定删除当前任务吗？',
          iconType: 'warning',
          onOk: async () => {
            await $http?.deleteWaylinejobDel(jobId)
            searchQuery()
          },
          onCancel: () => {},
        });
      }
    break;
    case 'viewWayLine':  // TODO: 需要杨柳那边做好轨迹详情!
      {
        const result = await $http?.getDeviceGet({ 
          deviceId: deviceId
        })
        if( result && result.deviceSn ) {
          trackPlaybackOpen.value = true
          trackPlaybackDeviceSn.value = result.deviceSn
        }
      }
    break;
  }
}

const enterSearch = (value) => {
  //console.log("查询文件==value", value)
  queryParam.jobName = value
  searchQuery()
}

const selectChange = (type: string, value?: any) => {
  //console.log("value222222222", value)
  switch(type){
    case "status":
      {
        queryParam.status = value ?? ''
        searchQuery()
      }
      break
    case "jobType":
      {
        queryParam.jobType = value ?? ''
        searchQuery()
      }
      break
  }
}

const searchTree = (tree: any) => {
  dirList.value.push({ 
    name: tree.directoryName,
    id: tree.id,
    dirType: tree.directoryType,
  })
  if(tree.children){
    searchTree(tree.children)
  }
}

const openDataManage = async(record) => {
  const result = await $http?.getDirectoryGetDirByJob({ jobId: record.id })
  dirList.value = []
  searchTree(result)
  //console.log("跳转到数据管理=====", dirList.value)
  sessionStorage.setItem(DataDirNavigation, JSON.stringify(dirList.value))
  router.push({
    path: '/dataManage/dataManage',
  })
}

function success() {
  searchQuery()
}

</script>
<style lang="less" scoped>
/deep/ .jeecg-basic-table-header__toolbar {
  width: auto;
}

/deep/ .cell-content::before {
  content: url('/@/assets/icons/FolderOpenFilled.svg');
  margin-right: 10px;
  vertical-align: middle;
}

/deep/ .cell-content {
  cursor: pointer
}

/deep/ .ant-table-thead>tr>th {
  background: #edf6fb;
  color: #0F699A;
}

/deep/ .ant-table-tbody>tr.ant-table-row:hover>td,
.ant-table-tbody>tr>td.ant-table-cell-row-hover {
  background: #f7fbfc;
}

/deep/ .ant-popover-buttons {
  display: flex;
}
.job-container-wrap{
  position: relative;
  display: flex;
  justify-content: space-between;
  .top-mod{
    width: 100%;
    background: #fff;
    .calendar{
      .calendar-top{
        height: 45px;
        display: flex;
        .title-wrap{
          display: flex;
          
          align-items: center;
          .title{
            width: 100px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 500;
            color: #333333;
            text-align: center;
          }
        }
      }
    }
  }
  
  .table-wrap{
    width: 75%;
    .customCol{
      .openDir:hover{
        cursor:pointer;
      }
    }
    .resultWrap{
      display: flex;
      justify-content: center;
      cursor: pointer;
      .resultNum{
        margin-left: 5px;
        color: #3eacef;
      }
    }
    .statusWrap{
      display: flex;
      justify-content: center;
      align-items: center;
      .text{

      }
      .tips{
        margin-top: 8px;
        margin-left: 5px;
      }
    }
    .toolbar{
      display: flex;
      margin-top: 3px;
      .icon{
          width: 120px;
          margin-right: 250px;
          display: flex;
          align-items: center;
          z-index: 1000;
          .icon-calendar{
            width: 38px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .icon-list{
            width: 38px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            background: linear-gradient(56deg, #2C9AD6 0%, #167DB5 100%);
            border-radius: 0px 16px 16px 0px;
          }
        }
      .addTask {
        background: linear-gradient(315deg, #2997d2 0%, #1880b9 100%);
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.16);
        border-radius: 2px;
        color: white;
      }
    }
  }
}
</style>
<style lang="less">
.job-container-wrap{
  .ant-picker-body{
    background: rgba(237,248,255,0.5);
    border-radius: 4px;
  }
}
</style>